package com.mama100.rpc.mdp.service.finagle;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;

import com.mama100.common.finagle.util.FinagleRPC;
import com.mama100.common.finagle.util.RpcUtil;
import com.mama100.rpc.mdp.MdpInoutUtil;
import com.mama100.rpc.mdp.constant.ResponseCode;
import com.mama100.rpc.mdp.thrift.inout.GetTCustBelongByCustomerIdRequest;
import com.mama100.rpc.mdp.thrift.inout.GetTCustBelongByCustomerIdResponse;
import com.mama100.rpc.mdp.thrift.inout.GetTCustBelongByTerminalCodeRequest;
import com.mama100.rpc.mdp.thrift.inout.GetTCustBelongByTerminalCodeResponse;
import com.mama100.rpc.mdp.thrift.inout.GetTCustBelongTerminalRequest;
import com.mama100.rpc.mdp.thrift.inout.TCustBelong;
import com.mama100.rpc.mdp.thrift.inout.common.BaseResponse;
import com.twitter.util.ExecutorServiceFuturePool;
import com.twitter.util.Function0;
import com.twitter.util.Future;

@FinagleRPC
@Service("custTerminalBelongService")
public class CustTerminalBelongService implements com.mama100.rpc.mdp.thrift.CustTerminalBelongService.ServiceIface{

	protected Logger log = LoggerFactory.getLogger(this.getClass());
	
	@Autowired
	private ExecutorServiceFuturePool futurePool;
	
	@Resource(name = "crmJdbcTemplate")
	JdbcTemplate jdbcTemplate;
	
	private String mergeSql = null;
	
	public CustTerminalBelongService(){
		// merge into
		StringBuffer sb = new StringBuffer();
		sb.append(" insert into mama100_owner.mdp_so_cust_terminal (id,customer_id,terminal_code,from_type,from_system,created_time,expiry_time,status,updated_time) values ( MDP_SO_CUST_TERMINAL_SEQ.nextval,?,?,?,?,sysdate,add_months(sysdate,12),?,sysdate ) ");
		mergeSql = sb.toString();
	}
	
	
	@Override
	public Future<BaseResponse> customerBelongTerminal(GetTCustBelongTerminalRequest req) {
		return futurePool.apply(new Function0<BaseResponse>() {
			@Override
			public BaseResponse apply() {
				BaseResponse resp = new BaseResponse();

				if (req.getBaseReq().getSeqNo() == null) {
					resp.setSeqNo(RpcUtil.genSeqNo());
				} else {
					resp.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					long customerId = req.getCustomerId();
					String terminalCode = req.getTerminalCode();
					int fromType = req.getFromType();
					String fromSystem = req.getFromSystem();
					String orderId = req.getOrderId();
					int status = 1;
					
					//门店不能为空
					if((terminalCode == null || "".equals(terminalCode) || "null".equals(terminalCode))){
						// 还没有APP行为
						resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
						resp.setRespDesc("会员:"+customerId+" 门店不能为空。");
						log.info("return:" + resp.toString());
						return resp;
					}
					
					//判断入口类型
					if(!(fromType == 1 || fromType == 3 || fromType == 4)){
						// 入口类型不是指定类型
						resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
						resp.setRespDesc("会员:"+customerId+" 入口类型不是指定类型。");
						log.info("return:" + resp.toString());
						return resp;
					}
					
					//品牌门店都不处理
					Long terminalCodeCount = jdbcTemplate.queryForObject(" select count(1) from mama100_owner.common_virual_terminal where terminal_code='"+terminalCode+"' and status=1 ",Long.class);
					if(terminalCodeCount>0){
						//门店是品版门店，不做处理
						resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
						resp.setRespDesc("会员:"+customerId+" 门店是品牌门店，不做处理");
						log.info("return:" + resp.toString());
						return resp;
					}
					
					//只有APP的购买行为才处理
					if(fromType == 4){
						//会员是否有归属
						Long orderCount = jdbcTemplate.queryForObject(" select count(1) from mama100_owner.common_cust_order where id='"+orderId+"'  and source_system in ('MOBILE', 'MAMA100_MOB_IPHONE','MAMA100_MOB_ANDRIOD','MAMA_MOB') and order_status = 7 ",
								Long.class);
						if(orderCount<=0){
							// 还没有APP行为
							resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
							resp.setRespDesc("会员:"+customerId+" 不是APP的购买行为，不归属门店");
							log.info("return:" + resp.toString());
							return resp;
						}
					}
					
					//会员是否有归属
					Long count = jdbcTemplate.queryForObject("select count(1) from mama100_owner.mdp_so_cust_terminal where customer_id = "+customerId+" and status = 1 and expiry_time > sysdate ",
							Long.class);
					
					if(count != null && count>=1){
						if(fromType == 4){
							// update 延长有效期
							int updated = jdbcTemplate.update("update  mama100_owner.mdp_so_cust_terminal set  expiry_time = add_months(sysdate,12) , updated_time=sysdate where customer_id =? and status = 1 and expiry_time > sysdate  ",customerId);
						}else{
							// 已经有归属门店
							resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
							resp.setRespDesc("会员:"+customerId+" 已经有归属门店");
							log.info("return:" + resp.toString());
							return resp;
						}
					}else{
						//是否有APP行为
						Long countApp = jdbcTemplate.queryForObject("select count(1) from mama100_owner.snsec_user_device_asso where customer_id = "+customerId,Long.class);
						if(countApp != null && countApp >=1){
							//失效后关注行为不影响归属只有发生购买才会重新归属
							if(fromType != 4){
								//会员是否有过期归属
								Long countOld = jdbcTemplate.queryForObject("select count(1) from mama100_owner.mdp_so_cust_terminal where customer_id = "+customerId,
										Long.class);
								if(countOld > 0){
									// 会员有过期归属
									resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
									resp.setRespDesc("会员:"+customerId+" 已存在失效归属门店，关注行不重新归属");
									log.info("return:" + resp.toString());
									return resp;
								}
							}
							//归属会员与门店
							jdbcTemplate.update(mergeSql, customerId, terminalCode, fromType, fromSystem, status);
						}else{
							// 还没有APP行为
							resp.setRespCode(ResponseCode.INVALID_REQUEST.getCode());
							resp.setRespDesc("会员:"+customerId+" 还没有APP行为");
							log.info("return:" + resp.toString());
							return resp;
						}
					}
				} catch (Exception e) {
					log.error("error:", e);
					resp.setRespCode(ResponseCode.SERVER_ERROR.getCode());
					resp.setRespDesc(ResponseCode.SERVER_ERROR.getDesc());
					log.info("return:" + resp);
					return resp;
				}
				resp.setRespCode(ResponseCode.SUCCESS.getCode());
				resp.setRespDesc(ResponseCode.SUCCESS.getDesc());
				log.info("return:" + resp.toString());
				return resp;
			}

		});
	}

	@Override
	public Future<GetTCustBelongByCustomerIdResponse> getTCustBelongByCustomerId(GetTCustBelongByCustomerIdRequest req) {
		return futurePool.apply(new Function0<GetTCustBelongByCustomerIdResponse>() {
			@Override
			public GetTCustBelongByCustomerIdResponse apply() {
				//GetTCustBelongByCustomerIdResponse resp = MdpInoutUtil.getGetTCustBelongByCustomerIdResponse(RpcUtil.genSeqNo());
				
				GetTCustBelongByCustomerIdResponse resp = new GetTCustBelongByCustomerIdResponse();
		        BaseResponse baseResp = MdpInoutUtil.getBaseResponse(RpcUtil.genSeqNo());
		        resp.setBaseResp(baseResp);
				
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					long customerId = req.getCustomerId();
					RowMapper<TCustBelong> rowMapper = new RowMapper<TCustBelong>() {
						@Override
						public TCustBelong mapRow(ResultSet rs, int rowNum) throws SQLException {
							TCustBelong cb = new TCustBelong();
							cb.setCustomerId(customerId);
							cb.setTerminalCode(rs.getString("terminal_code"));
							cb.setFromType(rs.getInt("from_type"));
							cb.setFromSystem(rs.getString("from_system") );
							cb.setCreatedTime(rs.getDate("created_time").getTime());
							cb.setExpiryTime(rs.getDate("expiry_time").getTime() );
							cb.setUpdatedTime(rs.getDate("updated_time").getTime() );
							return cb;
						}
					};
					String sql = "select terminal_code,from_type,from_system,created_time,expiry_time,status,updated_time from mama100_owner.mdp_so_cust_terminal where customer_id = ? and status = 1 and expiry_time > sysdate ";
					List<TCustBelong> values = jdbcTemplate.query(sql, new Object[] { customerId }, rowMapper);
					if(values != null && values.size()>=1){
						resp.setValue(values.get(0));
					}
				} catch (Exception e) {
					log.error("error:", e);
					base.setRespCode(ResponseCode.SERVER_ERROR.getCode());
					base.setRespDesc(ResponseCode.SERVER_ERROR.getDesc());
					log.info("return:" + resp);
					return resp;
				}
				base.setRespCode(ResponseCode.SUCCESS.getCode());
				base.setRespDesc(ResponseCode.SUCCESS.getDesc());
				log.info("return:" + resp.toString());
				return resp;
			}

		});
	}

	@Override
	public Future<GetTCustBelongByTerminalCodeResponse> getTCustBelongByTerminalCode(GetTCustBelongByTerminalCodeRequest req) {
		return futurePool.apply(new Function0<GetTCustBelongByTerminalCodeResponse>() {
			@Override
			public GetTCustBelongByTerminalCodeResponse apply() {
				GetTCustBelongByTerminalCodeResponse resp = MdpInoutUtil.getGetTCustBelongByTerminalCodeResponse(RpcUtil.genSeqNo());
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					String terminalCode = req.getTerminalCode();
					int firstResult = req.getFirstResult();
					int maxResult = req.getMaxResult();
					
					RowMapper<TCustBelong> rowMapper = new RowMapper<TCustBelong>() {
						@Override
						public TCustBelong mapRow(ResultSet rs, int rowNum) throws SQLException {
							TCustBelong cb = new TCustBelong();
							cb.setTerminalCode(terminalCode);
							cb.setCustomerId(rs.getLong("customer_id"));
							cb.setFromType(rs.getInt("from_type"));
							cb.setFromSystem(rs.getString("from_system") );
							cb.setCreatedTime(rs.getDate("created_time").getTime());
							cb.setExpiryTime(rs.getDate("expiry_time").getTime() );
							cb.setUpdatedTime(rs.getDate("updated_time").getTime() );
							return cb;
						}
					};
					String sql = "select * from ( select rownum as rowno,customer_id,from_type,from_system,created_time,expiry_time,status,updated_time from mama100_owner.mdp_so_cust_terminal where terminal_code = ?  and status = 1 and expiry_time > sysdate and rownum <= ?) where rowno > ? ";
					List<TCustBelong> value = jdbcTemplate.query(sql, new Object[] { terminalCode,firstResult+maxResult,firstResult }, rowMapper);
					resp.setValue(value);
				} catch (Exception e) {
					log.error("error:", e);
					base.setRespCode(ResponseCode.SERVER_ERROR.getCode());
					base.setRespDesc(ResponseCode.SERVER_ERROR.getDesc());
					log.info("return:" + resp);
					return resp;
				}
				base.setRespCode(ResponseCode.SUCCESS.getCode());
				base.setRespDesc(ResponseCode.SUCCESS.getDesc());
				log.info("return:" + resp.toString());
				return resp;
			}

		});
	}
	
	
	// 方法样例
	/*@Override
	public Future<GetTCustBelongByTerminalCodeResponse> getTCustBelongByTerminalCode(GetTCustBelongByTerminalCodeRequest req) {
		return futurePool.apply(new Function0<GetTCustBelongByTerminalCodeResponse>() {
			@Override
			public GetTCustBelongByTerminalCodeResponse apply() {
				GetCustBrandResponse resp = MdpInoutUtil.getGetCustBrandResponse(RpcUtil.genSeqNo());
				BaseResponse base = resp.getBaseResp();
				if (req.getBaseReq().getSeqNo() != null) {
					base.setSeqNo(req.getBaseReq().getSeqNo());
				}
				log.info("receive:" + req.toString());
				try {
					
				} catch (Exception e) {
					// TODO: handle exception
				}
				return null;
			}

		});
	}*/

}
